package com.ceair.authorization.wechat;

import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;

import java.util.Objects;
import java.util.function.Consumer;

import static com.ceair.constant.SecurityConstants.*;

/**
 * @author wangbaohai
 * @ClassName WechatAuthorizationRequestConsumer
 * @description: 自定义微信登录认证请求
 * @date 2024年11月27日
 * @version: 1.0.0
 */
public class WechatAuthorizationRequestConsumer implements Consumer<OAuth2AuthorizationRequest.Builder> {

    /**
     * 自定义OAuth2授权请求构建器
     * 该方法用于在构建授权请求时添加额外的参数或修改现有参数
     * 主要用于适应特定的OAuth2提供者要求，例如微信登录的特殊需求
     *
     * @param builder OAuth2授权请求的构建器，用于配置授权请求的各项参数
     */
    @Override
    public void accept(OAuth2AuthorizationRequest.Builder builder) {
        // 构建授权请求对象
        OAuth2AuthorizationRequest authorizationRequest = builder.build();
        // 获取注册ID，用于判断当前使用的OAuth2提供者
        Object registrationId = authorizationRequest.getAttribute(OAuth2ParameterNames.REGISTRATION_ID);
        // 检查是否为微信登录
        if (Objects.equals(registrationId, THIRD_LOGIN_WECHAT)) {
            // 判断是否微信登录，如果是微信登录则将appid添加至请求参数中
            builder.additionalParameters((params) -> params.put(WECHAT_PARAMETER_FORCE_POPUP, true));
            builder.additionalParameters((params) -> params.put(WECHAT_PARAMETER_APPID,
                    authorizationRequest.getClientId()));

            // 重置授权申请参数顺序，以满足微信登录的特定要求
            builder.parameters(params -> {
                params.clear();
                // 重置授权申请参数顺序
                params.put(WECHAT_PARAMETER_APPID, authorizationRequest.getClientId());
                params.put(OAuth2ParameterNames.REDIRECT_URI, authorizationRequest.getRedirectUri());
                params.put(OAuth2ParameterNames.RESPONSE_TYPE, authorizationRequest.getResponseType().getValue());
                params.put(OAuth2ParameterNames.SCOPE, String.join(" ", authorizationRequest.getScopes()));
                params.put(OAuth2ParameterNames.STATE, authorizationRequest.getState());
                params.put(WECHAT_PARAMETER_FORCE_POPUP, true);
            });
        }
    }

}
